/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cifar10.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.imageio.ImageIO;

/**
 *
 * @author mwh
 */
public class NamedImages implements Iterable<NamedImage> {

    List<File> files;

    public NamedImages(String path) {
        File fPath = new File(path);
        File[] filesArray = fPath.listFiles();
        SortedMap<Integer,File> sorted = new TreeMap<Integer, File>();
        for (File f : filesArray) {
            String fn = f.getName();
            String[] fields = fn.split("\\.");
            Integer num = Integer.parseInt(fields[0]);
            sorted.put(num, f);

        }
        files = new ArrayList<File>();
        for (File f : sorted.values()) {
            files.add(f);
        }
        
    }

    @Override
    public Iterator<NamedImage> iterator() {
       return new ImageIterator(files);
    }

    public class ImageIterator implements Iterator<NamedImage> {

        Iterator<File> fileIterator;

        NamedImage nextImage;

        public ImageIterator(List<File> filenames) {
            this.fileIterator = filenames.iterator();
            nextImage = null;
        }

        @Override
        public boolean hasNext() {
            nextImage = null;
            if (fileIterator.hasNext()) {
                try {
                    File f = fileIterator.next();
                    BufferedImage image = ImageIO.read(f);
                    nextImage = new NamedImage(image, f.getName());
                    return true;
                } catch (IOException ex) {

                    return false;
                }
            }
            return false;
        }

        @Override
        public NamedImage next() {
            NamedImage nimg = nextImage;
            nextImage = null;
            return nimg;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    }

}
